package com.wit.witmg.util;

import java.io.IOException;

//温度设置类
public class TemperatureController {
    private ModbusTCPClient client;
    private int unitId;

    public TemperatureController(String host, int port, int unitId) {
        this.client = new ModbusTCPClient(host, port);
        this.unitId = unitId;
    }

    /**
     * 设置单个温度值 - 使用功能码0x06
     * @param address 寄存器地址 (从1开始)
     * @param temperature 温度值 (根据设备精度可能需要缩放)
     */
    public boolean setSingleTemperature(int address, int temperature) throws IOException {
        byte[] request = client.createWriteSingleRegisterRequest(unitId, address, temperature);
        byte[] response = client.sendRequest(request);

        // 验证响应
        if (response.length >= 4 && response[0] == 0x06) {
            int respAddress = ((response[1] & 0xFF) << 8) | (response[2] & 0xFF);
            int respValue = ((response[3] & 0xFF) << 8) | (response[4] & 0xFF);

            return (respAddress == address - 1) && (respValue == temperature);
        }
        return false;
    }

    /**
     * 设置多个温度参数 - 使用功能码0x10
     * @param startAddress 起始寄存器地址
     * @param temperatures 温度值数组
     */
    public boolean setMultipleTemperatures(int startAddress, int[] temperatures) throws IOException {
        byte[] request = client.createWriteMultipleRegistersRequest(unitId, startAddress, temperatures);
        byte[] response = client.sendRequest(request);

        // 验证响应
        if (response.length >= 4 && response[0] == 0x10) {
            int respAddress = ((response[1] & 0xFF) << 8) | (response[2] & 0xFF);
            int respQuantity = ((response[3] & 0xFF) << 8) | (response[4] & 0xFF);

            return (respAddress == startAddress - 1) && (respQuantity == temperatures.length);
        }
        return false;
    }

    /**
     * 设置浮点数温度值 (32位)
     * 注意：需要根据设备的浮点数格式进行处理
     */
    public boolean setFloatTemperature(int startAddress, float temperature) throws IOException {
        // 将float转换为两个16位寄存器
        int intBits = Float.floatToIntBits(temperature);
        int[] registers = {
                (intBits >> 16) & 0xFFFF,  // 高16位
                intBits & 0xFFFF           // 低16位
        };

        return setMultipleTemperatures(startAddress, registers);
    }

    /**
     * 设置带小数点的温度值 (例如：25.5°C)
     * 通过缩放因子处理小数
     */
    public boolean setScaledTemperature(int address, double temperature, int scale) throws IOException {
        int scaledValue = (int) (temperature * scale);
        return setSingleTemperature(address, scaledValue);
    }

    public boolean connect() {
        return client.connect();
    }

    public void disconnect() {
        client.disconnect();
    }
}
